#!/usr/bin/env node

import { spawn } from 'child_process'
import path from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// 测试MCP服务
async function testMCPService() {
  console.log('🚀 开始测试MCP Schema Generator服务...\n')

  // 启动MCP服务
  const serverPath = path.join(__dirname, '../dist/index.js')
  const projectPath = path.join(__dirname, '../../') // 指向formily项目根目录

  console.log(`📁 项目路径: ${projectPath}`)
  console.log(`🔧 服务路径: ${serverPath}\n`)

  // 模拟MCP客户端请求
  const testRequests = [
    {
      name: 'scan_components',
      args: { projectPath }
    },
    {
      name: 'generate_schema',
      args: {
        projectPath,
        componentName: 'Input',
        options: { includeFormilyProps: true }
      }
    },
    {
      name: 'analyze_dependencies',
      args: { projectPath }
    }
  ]

  for (const request of testRequests) {
    console.log(`\n📋 测试工具: ${request.name}`)
    console.log(`📝 参数:`, JSON.stringify(request.args, null, 2))

    try {
      // 这里应该通过MCP协议发送请求
      // 由于这是测试脚本，我们直接调用生成器类
      const { SchemaGenerator } = await import('../dist/schema-generator.js')
      const generator = new SchemaGenerator(projectPath)

      switch (request.name) {
        case 'scan_components':
          const components = await generator.scanSchemas()
          console.log(`✅ 找到 ${components.length} 个组件`)
          components.slice(0, 5).forEach(comp => {
            console.log(`   - ${comp.name} (${comp.category || 'common'})`)
          })
          if (components.length > 5) {
            console.log(`   ... 还有 ${components.length - 5} 个组件`)
          }
          break

        case 'generate_schema':
          const allComponents = await generator.scanSchemas()
          const inputComponent = allComponents.find(c => c.name === 'Input')
          if (inputComponent) {
            const jsonSchema = generator.convertToJsonSchema(inputComponent.schema, request.args.options)
            console.log(`✅ 成功生成Input组件的JSON Schema`)
            console.log(`📊 Schema包含 ${Object.keys(jsonSchema.properties || {}).length} 个属性`)
          } else {
            console.log(`❌ 未找到Input组件`)
          }
          break

        case 'analyze_dependencies':
          const dependencies = await generator.analyzeDependencies()
          console.log(`✅ 分析了 ${Object.keys(dependencies).length} 个组件的依赖关系`)
          const componentsWithDeps = Object.entries(dependencies).filter(([_, deps]) => deps.length > 0)
          console.log(`📦 ${componentsWithDeps.length} 个组件有依赖关系`)
          break
      }
    } catch (error) {
      console.log(`❌ 测试失败:`, error.message)
    }
  }

  console.log('\n🎉 测试完成!')
}

// 检查构建文件是否存在
async function checkBuild() {
  const fs = await import('fs')
  const buildPath = path.join(__dirname, '../dist/index.js')

  if (!fs.existsSync(buildPath)) {
    console.log('❌ 构建文件不存在，请先运行: npm run build')
    process.exit(1)
  }
}

// 主函数
async function main() {
  try {
    await checkBuild()
    await testMCPService()
  } catch (error) {
    console.error('💥 测试过程中出现错误:', error)
    process.exit(1)
  }
}

main()
